from django.shortcuts import render
from django.views import View
from django import http
import logging
from django.core.cache import cache

from .models import Area
from utils.response_code import  RETCODE
from .constants import AREAS_CACHE_EXPIRES

logger = logging.getLogger('django')


# Create your views here.
class AreaView(View):
    def get(self, request):
        area_id = request.GET.get('area_id')
        if not area_id:
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    province_model_list = Area.objects.filter(parent_id__isnull=True)

                    province_list = []

                    for province_model in province_model_list:
                        province_dict = {
                            'id': province_model.id,
                            'name': province_model.name
                        }
                        province_list.append(province_dict)
                        cache.set('province_list', province_list, AREAS_CACHE_EXPIRES)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'Query failed'})
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'Ok', 'province_list': province_list})
        else:
            sub_data = cache.get('area_' + area_id)
            if not sub_data:
                try:
                    parent_model = Area.objects.get(id=area_id)
                     # subs_model_list = parent_model.subs.all()

                    subs_model_list = Area.objects.filter(parent_id=area_id)

                    subs_dict_list = []
                    for sub_model in subs_model_list:
                        sub_dict = {
                            'id': sub_model.id,
                            'name': sub_model.name
                        }
                        subs_dict_list.append(sub_dict)

                    subs = subs_dict_list

                    sub_data = {
                        'parent_id': parent_model.id,
                        'parent_name': parent_model.name,
                        'subs': subs
                    }

                    cache.set('area_' + area_id, sub_data, AREAS_CACHE_EXPIRES)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'Query failed'})

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'Ok', 'sub_data': sub_data})
